package han.proof;

import java.util.Arrays;
import java.util.List;

/**
 * @author: Han
 * @date: 2018/7/4 13:49
 * @dscription: Cookie仓库, 提供cookie
 */
public class CookieRepository {

    private List<Cookie> cookieList;
    private int index = 0;

    /**
     * 用cookie数组初始化对象
     *
     * @param cookies cookie数组
     */
    public CookieRepository(Cookie[] cookies) {
        cookieList = Arrays.asList(cookies);
    }

    public List<Cookie> getCookieList() {
        return cookieList;
    }

    /**
     * 获取未被封禁,未被使用的cookie
     *
     * @return cookie
     */
    public Cookie getCookie() {
        if (index == cookieList.size()) {
            index = 0;
        }

        for (int i = index; i < cookieList.size(); i++) {
            Cookie cookie = cookieList.get(i);
            int status = cookie.getStatus();
            if (status == 0) {
                //如果获取到cookie,索引+1,返回cookie
                index = i + 1;
                return cookie;
            }
            if (i == cookieList.size() - 1) {
                //如果i到头了,从新开始
                i = -1;
            }
            if (i == index - 1) {
                //如果整个数组被遍历过一遍都没有获取到cookie,跳出,并返回null
                break;
            }
        }
        return null;
    }

    public int[] getStatus() {
        int a = 0;
        int b = 0;
        int c = 0;
        for (Cookie cookie : cookieList) {
            int status = cookie.getStatus();
            if (status == 0) {
                a++;
            } else if (status == 1) {
                b++;
            } else {
                c++;
            }
        }

        return new int[]{a, b, c};
    }
}
